package com.budwk.app.sqfw.services.impl.SecurityInvestigationImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.GasA20Enum;
import com.budwk.app.sqfw.enums.SqfwFormSummaryFieldEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.services.SecurityInvestigationService;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwSummaryForAdminService;
import com.budwk.app.sqfw.services.impl.SqfwSummaryForAdminServiceImpl;
import com.budwk.app.sqfw.vo.Sqfw_formSummaryForAdminVO;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.CommonFormOfficeForAdminUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@IocBean(name = "huaGuoYuanStreetService")
@Slf4j
public class HuaGuoYuanStreeServiceImpl implements SecurityInvestigationService {

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;
    @Inject
    private SqfwSummaryForAdminService sqfwSummaryForAdminService;
    @Inject
    private CommunityStreetComponent communityStreetComponent;
    @Inject
    private SysUserService sysUserService;

    private static final String GUIZHOUS = "贵州省";

    private static final String GUIYAN = "贵阳市";

    private static final String NANMING = "南明区";

    private static final String ZHISHU = "直属";

    private static final String COUNTY = "花果园街道";

    @Override
    public Criteria buildQueryCond(Sqfw_formSummaryForAdminVO forAdminVo) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        criSql.andEquals(Sqfw_formSummaryForAdminVO::getType, SqfwFormSummaryConstants.safety_check)
                .andEquals(Sqfw_formSummaryForAdminVO::getCity, GUIYAN)
                .andEquals(Sqfw_formSummaryForAdminVO::getDistrict, NANMING)
                .andEquals(Sqfw_formSummaryForAdminVO::getCounty, COUNTY);
        // 组装查询条件
        if (Strings.isNotBlank(forAdminVo.getPageOrderName()) && Strings.isNotBlank(forAdminVo.getPageOrderBy())) {
            if (forAdminVo.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(forAdminVo.getPageOrderName());
            }
            if (forAdminVo.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(forAdminVo.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary::getFillDate);
        }
        // 辖区
        if (Strings.isNotBlank(forAdminVo.getCommunity())) {
            criSql.andLike(Sqfw_formSummary::getCommunity, forAdminVo.getCommunity());
        }
        // 时间
        communityStreetComponent.handleQueryTime(forAdminVo, criSql);
        // 场所名称 a1
        if (StringUtils.isNotEmpty(forAdminVo.getA1())) {
            criSql.andLike(Sqfw_formSummary::getA1, forAdminVo.getA1());
        }
        // 经营地址：在a3+a4+a5+a6+a7(第四列)中搜索包含关键字的内容；
        if (StringUtils.isNotEmpty(forAdminVo.getA3())) {
            SqlExpressionGroup a3 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA3, "like", "%" + forAdminVo.getA3() + "%");
            SqlExpressionGroup a4 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA4, "like", "%" + forAdminVo.getA3() + "%");
            SqlExpressionGroup a5 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA5, "like", "%" + forAdminVo.getA3() + "%");
            SqlExpressionGroup a6 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA6, "like", "%" + forAdminVo.getA3() + "%");
            SqlExpressionGroup a7 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA7, "like", "%" + forAdminVo.getA3() + "%");
            criSql.and(a3.or(a4).or(a5).or(a6).or(a7));
        }
        //  负责人 a2
        if (StringUtils.isNotEmpty(forAdminVo.getA2())) {
            criSql.andLike(Sqfw_formSummary::getA2, forAdminVo.getA2());
        }
        // 检查人员 createUserName
        if (StringUtils.isNotEmpty(forAdminVo.getCreateUserName())) {
            criSql.andLike(Sqfw_formSummary::getCreateUserName, forAdminVo.getCreateUserName());
        }
        // 场所类型 a16待确认清楚 属于枚举
        if (StringUtils.isNotEmpty(forAdminVo.getA16())) {
            criSql.andLike(Sqfw_formSummary::getA16, forAdminVo.getA16());
        }
        // 燃气使用情况：需要穷举： 全部 / 无 / 使用醇基 / 使用液化气 / 用电；搜索a20
        if (StringUtils.isNotEmpty(forAdminVo.getA20())) {
            if (!forAdminVo.getA20().equals(GasA20Enum.ALL.getName())) {
                criSql.andLike(Sqfw_formSummary::getA20, forAdminVo.getA20());
            }
        }
        // 风险评估： 需要穷举： 全部 / 无 /  一般风险 / 较大风险 / 重大风险 / 特大风险；可复选；搜索a17;
        if (StringUtils.isNotEmpty(forAdminVo.getA17())) {
            String[] a17s = forAdminVo.getA17().split(",");
            SqlExpressionGroup sqlExpressionGroup = new SqlExpressionGroup();
            for (String a17 : a17s) {
                SqlExpressionGroup a = Cnd.exps(Sqfw_formSummaryForAdminVO::getA17, "like", String.format("%s%s%s","%", a17, "%"));
                sqlExpressionGroup.or(a);
            }
            criSql.and(sqlExpressionGroup);
        }
        // 数据统计页面 隐患数据跳转过来查询列表使用 add by LJT 2023-11-16
        if(Strings.isNotBlank(forAdminVo.getIssueStatus()) && "statistic".equals(forAdminVo.getIssueStatus())) {
            criSql.andNotEquals(Sqfw_formSummary::getIssueStatus,null);
            criSql.andNotEquals(Sqfw_formSummary::getIssueStatus,"正常");
        }

        // 非数据统计页面 是否存在隐患 add by LJT 2023-12-07
        if(Strings.isNotBlank(forAdminVo.getIssueStatus()) && !"statistic".equals(forAdminVo.getIssueStatus())) {
            if ("是".equals(forAdminVo.getIssueStatus())) {
                criSql.andNotEquals(Sqfw_formSummary::getIssueStatus,null);
                criSql.andNotEquals(Sqfw_formSummary::getIssueStatus,"正常");
            } else if ("否".equals(forAdminVo.getIssueStatus())) {
                criSql.andEquals(Sqfw_formSummary::getIssueStatus, "正常");
            }
        }

        if (Strings.isNotBlank(forAdminVo.getQueryAll())) {
            String queryAll = forAdminVo.getQueryAll();
            SqlExpressionGroup a1 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA1, "like", "%" + queryAll + "%");
            SqlExpressionGroup a2 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA2, "like", "%" + queryAll + "%");
            SqlExpressionGroup a3 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA3, "like", "%" + queryAll + "%");
            SqlExpressionGroup a4 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA4, "like", "%" + queryAll + "%");
            SqlExpressionGroup a5 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA5, "like", "%" + queryAll + "%");
            SqlExpressionGroup a6 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA6, "like", "%" + queryAll + "%");
            SqlExpressionGroup a7 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA7, "like", "%" + queryAll + "%");
            SqlExpressionGroup createUserName = Cnd.exps(Sqfw_formSummaryForAdminVO::getCreateUserName, "like", "%" + queryAll + "%");
            SqlExpressionGroup a20 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA20, "like", String.format("%s%s%s","%", queryAll, "%"));
            SqlExpressionGroup a17 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA17, "like", String.format("%s%s%s","%", queryAll, "%"));
            SqlExpressionGroup a16 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA16, "like", String.format("%s%s%s","%", queryAll, "%"));
            SqlExpressionGroup community = Cnd.exps(Sqfw_formSummaryForAdminVO::getCommunity, "like", "%" + queryAll + "%");
            criSql.and(a1.or(a2).or(a3).or(a4).or(a5).or(a6).or(a7).or(createUserName).or(a20).or(a17).or(community).or(a16));
        }
        criSql.andNotEquals(Sqfw_formSummary::getFillDate, CommonConstants.WASTE_CREATE_TIME);

        // 如果是查询未超时数据，只查询7天前的数据（需求）
        if (Strings.isNotBlank(forAdminVo.getCheckStatus()) && SqfwSummaryForAdminServiceImpl.TO_DO_CHECK_OUT.equals(forAdminVo.getCheckStatus())) {
            criSql.andEquals(Sqfw_formSummary::getCheckStatus, forAdminVo.getCheckStatus());
            Date offsetDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(DateUtil.offsetDay(new Date(), -CommonFormOfficeForAdminUtils.TIME_OUT)));
            criSql.and(Sqfw_formSummary::getFillDate, "<", offsetDate);
            criSql.and("check_status","!=", SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode());
        }
        // 需求：增加是否超时检查情况 add by LJT 2024-01-16
        if (Strings.isNotBlank(forAdminVo.getCheckStatus()) && SqfwSummaryForAdminServiceImpl.CHECK_OUT.equals(forAdminVo.getCheckStatus())) {
            Date offsetDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(DateUtil.offsetDay(new Date(), -CommonFormOfficeForAdminUtils.TIME_OUT)));
            SqlExpressionGroup e1 = Cnd.exps("fill_date", ">=", offsetDate);
            SqlExpressionGroup e2 = Cnd.exps("check_status", "!=", SqfwSummaryForAdminServiceImpl.TO_DO_CHECK_OUT);
            criSql.and(e1.or(e2));
            criSql.and("check_status","!=", SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode());
        }
        if (Strings.isNotBlank(forAdminVo.getCheckStatus()) && SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode().equals(forAdminVo.getCheckStatus())) {
            criSql.and("check_status", "=", forAdminVo.getCheckStatus());
        }
        return cri;
    }

    @Override
    public Result<Pagination> listSummaryByPage(Sqfw_formSummaryForAdminVO forAdminVo) {
        // 构建查询条件
        Criteria cnd = buildQueryCond(forAdminVo);
        Pagination pagination = sqfwSummaryForAdminService.listPage(forAdminVo.getPageNo(), forAdminVo.getPageSize(), cnd);
        // 空值处理
        if (pagination.getTotalCount() > 0) {
            List<Sqfw_formSummary> results = new ArrayList<>(50);
            for (Sqfw_formSummary formSummary : pagination.getList(Sqfw_formSummary.class)) {
                results.add(StrUtil.formatSummaryNullStr(formSummary));
            }
            pagination.setList(results);
        }
        // 7天以内的数据状态改成2-已检查，前台方便展示
        if (Strings.isBlank(forAdminVo.getCheckStatus()) || SqfwSummaryForAdminServiceImpl.CHECK_OUT.equals(forAdminVo.getCheckStatus())) {
            List<Sqfw_formSummary> sqfwFormSummaryList = pagination.getList(Sqfw_formSummary.class);
            List<Sqfw_formSummaryForAdminVO> sqfwFormSummaryForAdminVOList = new ArrayList<Sqfw_formSummaryForAdminVO>();
            for (Sqfw_formSummary sqfwFormSummary : sqfwFormSummaryList) {
                Sqfw_formSummaryForAdminVO sqfwFormSummaryForAdminVO = new Sqfw_formSummaryForAdminVO();
                BeanUtil.copyProperties(sqfwFormSummary, sqfwFormSummaryForAdminVO);
                if (Strings.isNotBlank(sqfwFormSummary.getCheckStatus())
                        && SqfwSummaryForAdminServiceImpl.TO_DO_CHECK_OUT.equals(sqfwFormSummary.getCheckStatus().trim())
                        && null != sqfwFormSummaryForAdminVO.getFillDate()) {
                    Date offsetDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(DateUtil.offsetDay(new Date(), -CommonFormOfficeForAdminUtils.TIME_OUT)));
                    Date thisFillDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(sqfwFormSummaryForAdminVO.getFillDate()));
                    if (offsetDate.compareTo(thisFillDate) < 0) {
                        sqfwFormSummaryForAdminVO.setCheckStatus(SqfwSummaryForAdminServiceImpl.CHECK_OUT);
                    }
                }
                sqfwFormSummaryForAdminVOList.add(sqfwFormSummaryForAdminVO);
            }
            pagination.setList(sqfwFormSummaryForAdminVOList);
        }
        return Result.success(pagination);
    }

    @Override
    public boolean checkCurrentUserAuthority() {
        Sys_user user = sysUserService.fetch(SecurityUtil.getUserId());
        if (user == null) {
            throw new AppException(ResultCode.USER_NOT_FOUND.getMsg());
        }
        // 检查用户是否具有操作权限
        String province = user.getProvince();
        String city = user.getCity();
        String district = user.getDistrict();
        String county = user.getCounty();
        String community = user.getCommunity();

        // ○如果【province=贵州省】且【city=贵阳市】且【district=南明区】且【county=花果园】且【community=直属】时，可以看见数据统计页面。
        if (GUIZHOUS.equals(province) && GUIYAN.equals(city) && NANMING.equals(district) && COUNTY.equals(county) && ZHISHU.equals(community)) {
            return true;
        }
        //○如果【province=贵州省】且【city=贵阳市】且【district=南明区】且【county=直属】时，可以看见数据统计页面。
        if (GUIZHOUS.equals(province) && GUIYAN.equals(city) && NANMING.equals(district) && ZHISHU.equals(county)) {
            return true;
        }
        //○如果【province=贵州省】且【city=贵阳市】且【district=直属】时，可以看见数据统计页面。
        if (GUIZHOUS.equals(province) && GUIYAN.equals(city) && ZHISHU.equals(district)) {
            return true;
        }
        //○如果【province=贵州省】且【city=直属】时，可以看见数据统计页面。
        if (GUIZHOUS.equals(province) && ZHISHU.equals(city)) {
            return true;
        }
        //○如果【province=直属】时，可以看见数据统计页面。
        if (ZHISHU.equals(province)) {
            return true;
        }
        throw new AppException("无权限操作！");
    }

    @Override
    public String generateServiceRecordPdfCollZipForBM(Sqfw_formSummaryForAdminVO forAdminVo) {
        // 1 构建查询条件
        Criteria cnd = buildQueryCond(forAdminVo);
        // 按照条件导出PDF
        String pdfUrl = communityStreetComponent.generateServiceRecordPdfCollZipForBM(cnd);
        log.info("youzha generateServiceRecordPdfCollZipForBM generateServiceRecordPdfColl res: {}", pdfUrl);
        CommonComponent.insertDownRecordLog(JSONObject.toJSONString(forAdminVo), JSONObject.toJSONString(Result.data(pdfUrl)), "花果园街道：按照查询条件导出PDF文件", pdfUrl, null);
        return pdfUrl;
    }

    @Override
    public String generateServiceRecordExcelCollZipForBM(Sqfw_formSummaryForAdminVO bean) {
        Criteria cnd = buildQueryCond(bean);
        // 查询数据
        String excelUrl = communityStreetComponent.generateServiceRecordExcelCollZipForBM(bean, cnd);
        log.info("generateServiceRecordExcelCollZipForBM res: {}", excelUrl);
        CommonComponent.insertDownRecordLog(JSONObject.toJSONString(bean), JSONObject.toJSONString(Result.data(excelUrl)), "花果园街道：按照查询条件导出Excel文件", excelUrl, null);
        return excelUrl;
    }
}
